import { spawn } from 'child_process';
import { EventEmitter } from 'events';

export class RTSPHandler extends EventEmitter {
  constructor(mediasoupRouter, config) {
    super();
    this.router = mediasoupRouter;
    this.config = config;
    this.ffmpegProcess = null;
    this.plainTransport = null;
    this.videoProducer = null;
    this.audioProducer = null;
    this.isStreaming = false;
  }

  async startStream(rtspUrl) {
    try {
      console.log(`Starting RTSP stream from: ${rtspUrl}`);
      
      // 保存RTSP URL
      this.rtspUrl = rtspUrl;
      
      // 创建 Plain Transport 用于接收 FFmpeg 的 RTP 流
      await this.createPlainTransport();
      
      // 启动 FFmpeg 进程
      await this.startFFmpeg(rtspUrl);
      
      // 创建 Producers
      await this.createProducers();
      
      // 确保producer已创建成功
      if (!this.videoProducer) {
        throw new Error('Video producer not created successfully');
      }
      
      // 等待一段时间，确保producer真正可用
      await new Promise(resolve => setTimeout(resolve, 500));
      
      this.isStreaming = true;
      this.emit('streamStarted', {
        videoProducerId: this.videoProducer?.id,
        audioProducerId: this.audioProducer?.id
      });
      
      console.log('RTSP stream started successfully');
      return {
        success: true,
        videoProducerId: this.videoProducer?.id,
        audioProducerId: this.audioProducer?.id
      };
      
    } catch (error) {
      console.error('Failed to start RTSP stream:', error);
      await this.stopStream();
      throw error;
    }
  }

  async createPlainTransport() {
    console.log('Creating Plain Transport...');
    
    this.plainTransport = await this.router.createPlainTransport({
      listenIp: this.config.plainTransport.listenIp,
      rtcpMux: this.config.plainTransport.rtcpMux,
      comedia: this.config.plainTransport.comedia
    });

    console.log(`Plain Transport created:`, {
      id: this.plainTransport.id,
      tuple: this.plainTransport.tuple
    });
  }

  async startFFmpeg(rtspUrl) {
    return new Promise((resolve, reject) => {
      console.log('Starting FFmpeg process...');
      
      const rtpVideoPort = this.plainTransport.tuple.localPort;
      const rtpAudioPort = rtpVideoPort + 2; // 音频端口通常是视频端口+2
      
      // FFmpeg 命令参数 - 优化RTSP流处理
      const ffmpegArgs = [
        '-rtsp_transport', 'tcp', // 使用TCP传输，更稳定
        '-i', rtspUrl,
        '-an', // 暂时禁用音频，专注于视频
        '-c:v', 'libvpx', // VP8编码
        '-b:v', this.config.rtsp.ffmpegOptions.video.bitrate,
        '-maxrate', this.config.rtsp.ffmpegOptions.video.bitrate,
        '-bufsize', '2000k',
        '-vf', `scale=${this.config.rtsp.ffmpegOptions.video.width}:${this.config.rtsp.ffmpegOptions.video.height}`,
        '-r', this.config.rtsp.ffmpegOptions.video.fps,
        '-g', '30', // 减小GOP size，提高响应性
        '-keyint_min', '15',
        '-quality', 'realtime', // 实时质量
        '-speed', '5', // 提高编码速度
        '-error-resilient', '1', // 错误恢复
        '-f', 'rtp',
        '-payload_type', '96',
        '-ssrc', '11111111', // 固定SSRC
        `rtp://127.0.0.1:${rtpVideoPort}`
      ];

      console.log('FFmpeg command:', 'ffmpeg', ffmpegArgs.join(' '));

      this.ffmpegProcess = spawn('ffmpeg', ffmpegArgs, {
        stdio: ['pipe', 'pipe', 'pipe'] // 确保stdin可用于发送'q'命令
      });

      this.ffmpegProcess.stdout.on('data', (data) => {
        console.log(`FFmpeg stdout: ${data}`);
      });

      let resolved = false;

      this.ffmpegProcess.stderr.on('data', (data) => {
        const message = data.toString();
        console.log(`FFmpeg stderr: ${message}`);

        // 检查是否开始发送流 - 更准确的检测
        if (!resolved && (
          message.includes('Opening') ||
          message.includes('Stream mapping') ||
          message.includes('Press [q] to stop') ||
          message.includes('frame=')
        )) {
          resolved = true;
          console.log('FFmpeg stream started successfully');
          resolve();
        }

        // 检查错误
        if (message.includes('Connection refused') ||
            message.includes('No route to host') ||
            message.includes('Invalid data found')) {
          if (!resolved) {
            resolved = true;
            reject(new Error(`FFmpeg error: ${message}`));
          }
        }
      });

      this.ffmpegProcess.on('error', (error) => {
        console.error('FFmpeg process error:', error);
        reject(error);
      });

      this.ffmpegProcess.on('close', (code, signal) => {
        console.log(`FFmpeg process closed with code ${code}, signal ${signal}`);
        this.isStreaming = false;
        this.ffmpegProcess = null;
        this.emit('streamStopped');
      });

      this.ffmpegProcess.on('exit', (code, signal) => {
        console.log(`FFmpeg process exited with code ${code}, signal ${signal}`);
        this.isStreaming = false;
        this.ffmpegProcess = null;
      });

      // 给 FFmpeg 一些时间启动，如果没有其他信号则超时
      setTimeout(() => {
        if (!resolved) {
          resolved = true;
          console.log('FFmpeg startup timeout, assuming success');
          resolve();
        }
      }, 5000);
    });
  }

  async createProducers() {
    console.log('Creating Producers...');

    try {
      // 创建视频 Producer
      this.videoProducer = await this.plainTransport.produce({
        kind: 'video',
        rtpParameters: {
          codecs: [
            {
              mimeType: 'video/VP8',
              clockRate: 90000,
              payloadType: 96,
              parameters: {}
            }
          ],
          encodings: [
            {
              ssrc: 11111111,
              rtx: {
                ssrc: 11111112
              }
            }
          ],
          headerExtensions: [],
          rtcp: {
            cname: 'mediasoup-rtsp-stream'
          }
        }
      });

      console.log('Video Producer created:', this.videoProducer.id);

      this.videoProducer.on('transportclose', () => {
        console.log('Video Producer transport closed');
      });

      this.videoProducer.on('score', (score) => {
        console.log(`Video Producer score:`, score);
      });

      // 暂时不创建音频 Producer，专注于视频
      // 后续可以添加音频支持

    } catch (error) {
      console.error('Failed to create producers:', error);
      throw error;
    }
  }

  async stopStream() {
    console.log('Stopping RTSP stream...');

    this.isStreaming = false;

    // 停止 FFmpeg 进程
    if (this.ffmpegProcess && !this.ffmpegProcess.killed) {
      console.log('Terminating FFmpeg process...');

      // 首先尝试优雅关闭
      this.ffmpegProcess.stdin.write('q');
      this.ffmpegProcess.stdin.end();

      // 等待一段时间后强制关闭
      setTimeout(() => {
        if (this.ffmpegProcess && !this.ffmpegProcess.killed) {
          console.log('Force killing FFmpeg process...');
          this.ffmpegProcess.kill('SIGKILL');
        }
      }, 2000);

      this.ffmpegProcess = null;
    }

    // 关闭 Producers
    if (this.videoProducer) {
      this.videoProducer.close();
      this.videoProducer = null;
    }

    if (this.audioProducer) {
      this.audioProducer.close();
      this.audioProducer = null;
    }

    // 关闭 Plain Transport
    if (this.plainTransport) {
      this.plainTransport.close();
      this.plainTransport = null;
    }

    this.emit('streamStopped');
    console.log('RTSP stream stopped');
  }

  getProducers() {
    return {
      video: this.videoProducer,
      audio: this.audioProducer
    };
  }

  isStreamActive() {
    return this.isStreaming && this.ffmpegProcess && !this.ffmpegProcess.killed;
  }

  // 获取当前RTSP URL
  getRtspUrl() {
    return this.rtspUrl;
  }
}
